package com.hmall.item.service.impl;

import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Override
    public List<Item> getItems(int page, int size) {
        int start = (page - 1) * size;
        return itemMapper.getItems(start, size);
    }


    @Override
    public void updateItem(Item item) {
        itemMapper.update(item);
    }

    @Override
    public int removeById(Long id) {
        return itemMapper.deleteById(id);
    }

    @Override
    public long getTotal() {
        return itemMapper.count();
    }

    @Override
    public void updateStatus(Long id, Long status) {
        itemMapper.updateStatus(id, status);
    }

    @Override
    public Item getById(Long id) {
        return itemMapper.getById(id);
    }

    @Override
    public List<Object> getCategory() {
        List<String> category = itemMapper.getCategory();
        //去重
        List<Object> collect = category.stream().distinct().collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<Object> getBrand() {
        List<String> brand = itemMapper.getBrand();
        //去重
        List<Object> collect = brand.stream().distinct().collect(Collectors.toList());
        return collect;
    }

    @Override
    public void updateStock(Long itemId, Integer num) {
        //先根据id查询商品信息
        Item item = itemMapper.getById(itemId);
        //修改商品库存
        item.setStock(item.getStock() - num);
        //根据id更新商品信息
        itemMapper.update(item);
    }

    /**
     * 添加商品
     *
     * @param item
     */
    @Override
    public void addItem(Item item) {
        itemMapper.save(item);
    }
}
